const {executeQuery} = require('../config/db_config')
const express = require('express')
const goodsRouter = express.Router()
goodsRouter.use(express.json())



goodsRouter.delete("/",async (req,resp)=>{
  const sql = `delete from goods where id=${req.query.id}`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:"success",
    data:[]
  })

})
/**
 * 添加商品
 */
goodsRouter.post("/",async(req,resp)=>{
  const sql = `insert into goods(img,title,price,des,type) values('${req.body.data.img}',
  ${escape(req.body.data.title)},${req.body.data.price},'${escape(req.body.data.des)}',${req.body.data.type})`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:"success",
    data:res
  })
})

/**
 * 获取指定种类的商品列表
 */
goodsRouter.get("/",async (req,resp)=>{
  console.log(req.session);
  const key = req.query.key
  const type = req.query.id
  const limit = req.query.limit
  const startIndex = (req.query.now_page-1)*limit
  const sql = `select * from goods where ${type?`type=${type}`:'1=1'}  and title like '%${key}%' limit ${startIndex},${limit}`
  const sql1 = `select count(*) as num from goods where ${type?`type=${type}`:'1=1'}   and title like '%${key}%'`
  const res = await executeQuery(sql)
  const res1 = await executeQuery(sql1)
  resp.send({
    code:200,
    msg:"success",
    data:{
      total:res1[0]?.num,
      list:res
    }
  })
})
/**
 * 获取指定类型指定商品详情
 */
goodsRouter.get("/detail",async (req,resp)=>{
  const type = req.query.type
  const id = req.query.id
  const sql = `select * from goods where type=${type} and id=${id}`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:"success",
    data:res[0]
  })
})
/**
 * 根据id获取商品
 */
goodsRouter.get("/id",async (req,resp)=>{
  const sql = `select * from goods where id=${req.query.id}`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:"success",
    data:res[0]
  })
})
/**
 * 根据关键字来查询商品
 */
goodsRouter.get("/:key",async (req,resp)=>{
  
  const sql = `select * from goods where title like '%${escape(req.params.key)}%'`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:"success",
    data:res
  })
})

module.exports={
  goodsRouter
}